/**
 * @fileoverview Electron API Hook - 提供渲染进程与主进程通信的接口
 * @description 封装了平台管理、账号管理、登录、视频上传等功能的API调用
 * @author Easy Share Web
 * @date 2024
 */

import { useState, useEffect } from 'react';

/**
 * Electron API 接口定义
 * 定义了所有可用的主进程通信方法
 */
interface ElectronAPI {
  // 平台管理
  getPlatforms: () => Promise<any[]>;
  addPlatform: (platform: any) => Promise<void>;
  removePlatform: (platformId: string) => Promise<void>;
  
  // 账号管理
  getAccounts: () => Promise<any[]>;
  addAccount: (account: any) => Promise<void>;
  removeAccount: (accountId: string) => Promise<void>;
  
  // 扫码登录
  startQRLogin: (platform: string) => Promise<{ sessionId: string; qrCode: string }>;
  getLoginStatus: (sessionId: string) => Promise<any>;
  
  // 内置浏览器登录
  openBrowserLogin: (platform: string) => Promise<{loginUrl: string}>;
  
  // 视频上传
  uploadVideo: (filePath: string, metadata: any) => Promise<string>;
  publishVideo: (videoId: string, platforms: string[]) => Promise<void>;
  
  // 进度监听
  onUploadProgress: (callback: (progress: any) => void) => void;
  onPublishProgress: (callback: (progress: any) => void) => void;
  
  // 打印功能
  print: () => Promise<any>;
  printToPDF: () => Promise<any>;
}

/**
 * useElectronAPI Hook
 * @description 提供与Electron主进程通信的API接口
 * @returns {ElectronAPI} 包含所有可用API方法的对象
 */
export const useElectronAPI = (): ElectronAPI => {
  const [isElectron, setIsElectron] = useState(false);

  /**
   * 检测是否在Electron环境中运行
   */
  useEffect(() => {
    setIsElectron(typeof window !== 'undefined' && !!window.electronAPI);
  }, []);

  const api: ElectronAPI = {
    /**
     * 获取所有平台列表
     * @returns {Promise<any[]>} 平台列表
     */
    getPlatforms: async () => {
      if (typeof window !== 'undefined' && window.electronAPI) {
        return await window.electronAPI.getPlatforms();
      }
      // 模拟数据
      return [
        { id: 'douyin', name: '抖音', displayName: '抖音', icon: '🎵', enabled: true },
        { id: 'bilibili', name: '哔哩哔哩', displayName: '哔哩哔哩', icon: '📺', enabled: true },
        { id: 'xiaohongshu', name: '小红书', displayName: '小红书', icon: '📒', enabled: true }
      ];
    },

    /**
     * 添加新平台
     * @param {any} platform 平台信息
     */
    addPlatform: async (platform: any) => {
      if (typeof window !== 'undefined' && window.electronAPI) {
        await window.electronAPI.addPlatform(platform);
      }
    },

    /**
     * 删除平台
     * @param {string} platformId 平台ID
     */
    removePlatform: async (platformId: string) => {
      if (typeof window !== 'undefined' && window.electronAPI) {
        await window.electronAPI.removePlatform(platformId);
      }
    },

    /**
     * 获取所有账号列表
     * @returns {Promise<any[]>} 账号列表
     */
    getAccounts: async () => {
      if (typeof window !== 'undefined' && window.electronAPI) {
        return await window.electronAPI.getAccounts();
      }
      return [];
    },

    /**
     * 添加新账号
     * @param {any} account 账号信息
     */
    addAccount: async (account: any) => {
      if (typeof window !== 'undefined' && window.electronAPI) {
        await window.electronAPI.addAccount(account);
      }
    },

    /**
     * 删除账号
     * @param {string} accountId 账号ID
     */
    removeAccount: async (accountId: string) => {
      if (typeof window !== 'undefined' && window.electronAPI) {
        await window.electronAPI.removeAccount(accountId);
      }
    },

    /**
     * 开始二维码登录
     * @param {string} platform 平台名称
     * @returns {Promise<{sessionId: string; qrCode: string}>} 登录会话信息
     */
    startQRLogin: async (platform: string) => {
      if (typeof window !== 'undefined' && window.electronAPI) {
        return await window.electronAPI.startQRLogin(platform);
      }
      // 模拟扫码登录
      return {
        sessionId: 'mock-session-' + Date.now(),
        qrCode: ''
      };
    },

    /**
     * 获取登录状态
     * @param {string} sessionId 会话ID
     * @returns {Promise<any>} 登录状态信息
     */
    getLoginStatus: async (sessionId: string) => {
      if (typeof window !== 'undefined' && window.electronAPI) {
        return await window.electronAPI.getLoginStatus(sessionId);
      }
      // 模拟登录状态
      return {
        status: 'success',
        username: 'test_user',
        token: 'mock-token-' + Date.now()
      };
    },

    /**
     * 上传视频文件
     * @param {string} filePath 视频文件路径
     * @param {any} metadata 视频元数据
     * @returns {Promise<string>} 上传任务ID
     */
    uploadVideo: async (filePath: string, metadata: any) => {
      if (typeof window !== 'undefined' && window.electronAPI) {
        return await window.electronAPI.uploadVideo(filePath, metadata);
      }
      // 模拟上传
      return 'task-' + Date.now();
    },

    /**
     * 发布视频到指定平台
     * @param {string} videoId 视频ID
     * @param {string[]} platforms 目标平台列表
     */
    publishVideo: async (videoId: string, platforms: string[]) => {
      if (typeof window !== 'undefined' && window.electronAPI) {
        await window.electronAPI.publishVideo(videoId, platforms);
      }
    },

    /**
     * 获取平台登录URL
     * @param {string} platform 平台名称
     * @returns {Promise<{loginUrl: string}>} 登录URL
     */
    openBrowserLogin: async (platform: string): Promise<{loginUrl: string}> => {
      if (typeof window !== 'undefined' && window.electronAPI) {
        return await window.electronAPI.openBrowserLogin(platform);
      } else {
        // 模拟返回登录URL
        console.log('模拟获取登录URL:', platform);
        return { loginUrl: `https://www.${platform}.com/login` };
      }
    },

    /**
     * 监听上传进度
     * @param {function} callback 进度回调函数
     */
    onUploadProgress: (callback: (progress: any) => void) => {
      if (typeof window !== 'undefined' && window.electronAPI && window.electronAPI.onUploadProgress) {
        window.electronAPI.onUploadProgress(callback);
      }
    },

    /**
     * 监听发布进度
     * @param {function} callback 进度回调函数
     */
    onPublishProgress: (callback: (progress: any) => void) => {
      if (typeof window !== 'undefined' && window.electronAPI && window.electronAPI.onPublishProgress) {
        window.electronAPI.onPublishProgress(callback);
      }
    },

    /**
     * 打印当前页面
     * @returns {Promise<any>} 打印结果
     */
    print: async () => {
      if (typeof window !== 'undefined' && window.electronAPI && window.electronAPI.print) {
        return await window.electronAPI.print();
      }
      // 浏览器环境下使用window.print()
      window.print();
      return { success: true, message: '使用浏览器打印功能' };
    },

    /**
     * 导出为PDF
     * @returns {Promise<any>} 导出结果
     */
    printToPDF: async () => {
      if (typeof window !== 'undefined' && window.electronAPI && window.electronAPI.printToPDF) {
        return await window.electronAPI.printToPDF();
      }
      // 浏览器环境下的模拟实现
      console.log('浏览器环境不支持PDF导出');
      return { success: false, message: '浏览器环境不支持PDF导出' };
    }
  };

  return api;
};

/**
 * 全局类型声明
 * 为window对象添加electronAPI属性的类型定义
 */
declare global {
  interface Window {
    electronAPI?: ElectronAPI;
  }
}
